package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.dto.userToken;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

import static com.cskaoyan.user.constants.UserRetCode.*;
import static com.cskaoyan.user.constants.UserRetCode.USER_ISVERFIED_ERROR;

@Service
public class ILoginServiceImpl implements ILoginService {
    @Autowired
    MemberMapper memberMapper;
    @Autowired
    UserConverterMapper userConverterMapper;

    @Override
    public UserLoginResponse login(UserLoginRequest request) {
        Example example = new Example(Member.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("password", DigestUtils.md5DigestAsHex(request.getUserPwd().getBytes()));
        criteria.andEqualTo("username", request.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (members.size() != 1) {
            throw new ValidateException(USERORPASSWORD_ERRROR.getCode(), USERORPASSWORD_ERRROR.getMessage());
        }
        if ("N".equals(members.get(0).getIsVerified())){
            throw new ValidateException(USER_ISVERFIED_ERROR.getCode(), USER_ISVERFIED_ERROR.getMessage());
        }
        UserLoginResponse converter = userConverterMapper.converter(members.get(0));
        userToken userToken = new userToken();
        userToken.setUid(converter.getId());
        userToken.setUsername(converter.getUsername());
        String s = JSON.toJSONString(userToken);
        System.out.println(s);
        System.out.println("-----------------");
        String msg = JwtTokenUtils.builder().msg(s).build().creatJwtToken();
        System.out.println(msg);
        String Decodedmsg = JwtTokenUtils.builder().token(msg).build().freeJwt();
        System.out.println(Decodedmsg);
        converter.setToken(msg);
        return converter;
    }

    @Override
    public userToken loginV(String msg) {
        userToken token = JSON.parseObject(msg, userToken.class);
        Member member = memberMapper.selectByPrimaryKey(token.getUid());
        userToken userToken = new userToken();
        userToken.setUid(member.getId());
        userToken.setUsername(member.getUsername());
        return userToken;
    }
}
